import { contextBridge, ipcRenderer, clipboard, nativeImage } from 'electron';
import { electronAPI } from '@electron-toolkit/preload';

// Custom APIs for renderer
const api = {};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
console.log('contextIsolated:', process.contextIsolated);

if (process.contextIsolated) {
    try {
        contextBridge.exposeInMainWorld('electron', electronAPI);
        contextBridge.exposeInMainWorld('api', api);
        contextBridge.exposeInMainWorld('electronAPI', {
            // 改变窗口大小
            netIsOnline: () => ipcRenderer.send('net-isOnline'),
            // 窗口设置鼠标是否可以穿透
            windowSetOpcaty: (num: number) => ipcRenderer.send('window-setOpcaty', num),
            windowChange: (w: number, h: number) => ipcRenderer.send('window-change', w, h),
            // 最小化窗口
            windowMinimize: () => ipcRenderer.send('window-minimize'),
            // 切换全屏
            windowFullScreen: () => ipcRenderer.send('window-fullScreen'),
            // 隐藏窗口
            windowHide: () => ipcRenderer.send('window-hide'),
            // 关闭窗口
            windowClose: () => ipcRenderer.send('window-close'),
            // 窗口切换为最大化状态
            windowFullMax: () => ipcRenderer.send('window-fullMax'),
            // 窗口恢复原来状态
            windowRestore: () => ipcRenderer.send('window-restore'),
            // 窗口恢复原来状态
            window_full_size: (isFull: boolean) => ipcRenderer.send('window_full_size', isFull),
            // 窗口改变背景色
            windowBackgroundColor: (color: string) =>
                ipcRenderer.send('window-backgroundColor', color),
            // 窗口设置鼠标是否可以穿透
            windowSetIgnoreMouseEvents: (flag: boolean) =>
                ipcRenderer.send('window-setIgnoreMouseEvents', flag),
            // 窗口设置是否置顶
            windowSetAlwaysOnTop: (flag: boolean) =>
                ipcRenderer.send('window-setAlwaysOnTop', flag),
            // 创建新窗口
            windowNew: (params: any) => ipcRenderer.send('window-new', params),
            // 渲染进程向主进程发送消息,主进程再返回消息（双向带参数）
            ipcToMainRenderer: (params: any) => ipcRenderer.invoke('ipc-toMainRenderer', params),
            // 主进程向渲染进程发送消息
            ipcToRenderer: (callback: any) => ipcRenderer.on('ipc-toRenderer', callback),
            // 渲染进程向渲染进程发送消息
            ipcToRendererRenderer: (params: any) =>
                ipcRenderer.send('ipc-toRendererRenderer', params),
            ipcToRendererRenderer2: (callback: any) =>
                ipcRenderer.on('ipc-toRendererRenderer2', callback),

            // 更新
            //获取当前版本
            appVersion: () => ipcRenderer.invoke('app-version'),

            // 检查更新
            updateCheck: (url: string) => ipcRenderer.send('update-check', url),
            // 检查更新提示信息
            updateMessage: (callback: any) => ipcRenderer.on('update-message', callback),
            // 检查更新下载进度
            updateDownloadProgress: (callback: any) =>
                ipcRenderer.on('update-downloadProgress', callback),
            // 检查更新完成，退出并安装
            updateQuitAndInstall: () => ipcRenderer.send('update-quitAndInstall'),

            // 发送系统通知
            notificationMain: () => ipcRenderer.send('notification-main'),

            // 文件
            // 获取文件默认存放路径
            appGetDefaultPath: () => ipcRenderer.invoke('app-getDefaultPath'),
            // 设置文件默认存放路径
            appSetDefaultPath: (filePath: string) =>
                ipcRenderer.send('app-setDefaultPath', filePath),
            // 打开文件并读取选择的文件名路径（可多选）
            dialogOpenFile: () => ipcRenderer.invoke('dialog-openFile'),
            // 打开文件夹并读取选择的文件夹路径
            dialogOpenFolder: () => ipcRenderer.invoke('dialog-openFolder'),
            // 保存文件并读取选择的文件目录
            dialogSaveFile: () => ipcRenderer.invoke('dialog-saveFile'),
            // 打开文件目录选择图片
            dialogImageFile: () => ipcRenderer.invoke('dialog-openImageFile'),

            // 打开一个网址
            shellOpenExternal: (filePath: string) =>
                ipcRenderer.send('shell-openExternal', filePath),
            // 打开指定文件夹或者文件
            shellOpenPath: (filePath: string) => ipcRenderer.send('shell-openPath', filePath),
            // 显示指定的文件
            shellOpenFolder: (filePath: string) => ipcRenderer.send('shell-showFolder', filePath),

            // startDrag: (fileName) => {
            //     ipcRenderer.send('ondragstart', path.join(process.cwd(), fileName))

            // }
            // startDrag: (fileName) => {
            //     ipcRenderer.send('ondragstart', fileName)
            //   }

            // 硬件
            // 获取主显示器信息
            screenMainMessage: () => ipcRenderer.invoke('screen-mainMessage'),
            // 获取成比例获得的窗口
            // screenMainSize: () => ipcRenderer.invoke('screen-mainSize'),
            // 检测麦克风，查看麦克风是否授权
            setCheckMicrophone: (mediaType: string) =>
                ipcRenderer.invoke('system-getMediaAccessStatus', mediaType),
            // 请求访问麦克风
            askCheckMicrophone: (mediaType: string) =>
                ipcRenderer.invoke('system-askForMediaAccess', mediaType),

            // WebRTC
            // 获取共享屏幕时的窗口信息
            // navigatorShare: (type) => desktopCapturer.getSources({ types: type,thumbnailSize: { width: 0, height: 0 }}),// ,
            navigatorShare: (type: any) => ipcRenderer.invoke('navigatorShare', type),
            // navigatorCurrentShare: (type) => desktopCapturer.getSources({ types: type,thumbnailSize: { width: 0, height: 0 }}),// ,
            navigatorCurrentWindowShare: () => ipcRenderer.invoke('navigatorCurrentWindowShare'),
            macScreenAllow: (mediaType: string) =>
                ipcRenderer.invoke('mac-screen-allow', mediaType),
            nativeImage: (url: string) => nativeImage.createFromPath(url),

            browserView: () => ipcRenderer.send('browser-view'),
            // 主进程拦截微信登录成功后的地址
            mainProcessWebRequest: (callback: any) =>
                ipcRenderer.on('main-process-webRequest', callback),

            // 复制
            clipboardCopy: (value: any) => clipboard.writeText(value),
            // 粘贴
            clipboardPaste: () => clipboard.readText(),

            // 禁止关闭窗口
            // notAllowClose: (e) => {
            //     console.log("禁止关闭窗口",e);
            //     ipcRenderer.on('notAllowClose', e)
            // }
            systemPermission: () => ipcRenderer.send('system-permission'),

            // 存储数据
            setLocalStore: (options: any, data: any) =>
                ipcRenderer.send('setLocalStore', options, data),
            // 获取数据
            getLocalStore: (options: any, data: any) =>
                ipcRenderer.invoke('getLocalStore', options, data),
            // 读取本地文件
            asyncGetLocalServer: (file: any) => ipcRenderer.send('asyncGetLocalServer', file),
            // 读取本地文件后的文件内容回调
            asyncBackLocalServer: (callback: any) =>
                ipcRenderer.on('asyncBackLocalServer', callback),
            // 移除ipcRenderer.on的所有相关监听事件
            removeAllListeners: (name: string) => ipcRenderer.removeAllListeners(name),

            // 截取主窗口屏幕
            screenshot: () => ipcRenderer.send('screenshot'),
            // 截取主窗口屏幕后的文件路径回调
            screenshot_path: (callback: any) => ipcRenderer.on('screenshot_path', callback)
        });
    } catch (error) {
        console.error(error);
    }
} else {
    // @ts-ignore (define in dts)
    window.electron = electronAPI;
    // @ts-ignore (define in dts)
    window.api = api;
}

